package com.holike.crm.activity.message;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.CookieManager;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.holike.crm.R;
import com.holike.crm.base.BaseFragment;
import com.holike.crm.base.BaseActivity;
import com.holike.crm.bean.MessageDetailsBean;
import com.holike.crm.presenter.activity.MessageDetailsPresenter;
import com.holike.crm.util.Constants;
import com.holike.crm.view.activity.MessageDetailsView;
import com.umeng.analytics.MobclickAgent;


/**
 * 消息详情
 */
public class MessageDetailsActivity extends BaseActivity<MessageDetailsPresenter, MessageDetailsView> implements MessageDetailsView {
    private LinearLayout mContainer;
    private String mType;
    private WebView mWebView;

    /**
     * 打开公告详情
     */
    public static void open(BaseFragment<?, ?> fragment, String messageId, String type, int requestCode) {
        if (fragment.getActivity() == null) return;
        MobclickAgent.onEvent(fragment.getActivity(), "message_announce_details");
        Intent intent = new Intent(fragment.getActivity(), MessageDetailsActivity.class);
        intent.putExtra(Constants.MESSAGE_ID, messageId);
        intent.putExtra("type", type);
        fragment.openActivityForResult(intent, requestCode, null);
    }

    @Override
    protected MessageDetailsPresenter attachPresenter() {
        return new MessageDetailsPresenter();
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_message_details;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mType = getIntent().getStringExtra("type");
        if (TextUtils.equals(mType, "2")) { //公告
            setTitle(R.string.message_system_message);
        } else if (TextUtils.equals(mType, "3")) { //新闻
            setTitle(R.string.message_news_type);
        } else if (TextUtils.equals(mType, "4")) { //百宝箱
            setTitle(R.string.message_treasure_chest);
        } else { //未知类型
            setTitle(R.string.details);
        }
        mContainer = findViewById(R.id.ll_content_layout);
        initData();
    }

    private void initData() {
        showLoading();
        String messageId = getIntent().getStringExtra(Constants.MESSAGE_ID);
        mPresenter.getMessageDetails(messageId, mType);
    }

    /**
     * 获取消息详情成功
     */
    @Override
    public void getMessageDetailsSuccess(MessageDetailsBean bean) {
        dismissLoading();
        updateMessageContent(bean);
    }

    private void updateMessageContent(MessageDetailsBean bean) {
        mContainer.removeAllViews();
        View headView = getLayoutInflater().inflate(R.layout.header_message_detail, mContainer, true);
        TextView tvTitle = headView.findViewById(R.id.tv_message_title);
        tvTitle.setText(bean.title);
        TextView tvDate = headView.findViewById(R.id.tv_message_date);
        tvDate.setText(bean.createDate);
        TextView tvSender = headView.findViewById(R.id.tv_message_sender);
        String publisher = getString(R.string.message_publisher);
        if (!TextUtils.isEmpty(bean.name))
            publisher += bean.name;
        tvSender.setText(publisher);
        mWebView = new WebView(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        lp.leftMargin = getResources().getDimensionPixelSize(R.dimen.dp_10);
        lp.rightMargin = getResources().getDimensionPixelSize(R.dimen.dp_10);
        mWebView.setLayoutParams(lp);
        initSettings();
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                mWebView.removeCallbacks(mReloadCallback);
                mWebView.postDelayed(mReloadCallback, 1000);
            }
        });
        mWebView.loadDataWithBaseURL(bean.baseUrl, bean.getHtml(this), "text/html", "UTF-8", null);
        mContainer.addView(mWebView);
//        WrapperRecyclerView recyclerView = obtain();
//        View headView = getLayoutInflater().inflate(R.layout.header_message_detail, recyclerView, false);
//        TextView tvTitle = headView.findViewById(R.id.tv_message_title);
//        tvTitle.setText(bean.title);
//        TextView tvDate = headView.findViewById(R.id.tv_message_date);
//        tvDate.setText(bean.createDate);
//        TextView tvSender = headView.findViewById(R.id.tv_message_sender);
//        String publisher = getString(R.string.message_publisher);
//        if (!TextUtils.isEmpty(bean.name))
//            publisher += bean.name;
//        tvSender.setText(publisher);
//        recyclerView.addHeaderView(headView);
//        recyclerView.setAdapter(new ImageAdapter(this, bean.getPictureList()));
//        mContainer.addView(recyclerView);
    }

    private void initSettings() {
        WebSettings webSettings = mWebView.getSettings();
        //网页有缩放的需求才会体现出此特性，比如访问的是电脑版网页
        webSettings.setSupportZoom(true);
        //将图片调整到适合webView的大小
        webSettings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);
        //默认也都是开
        webSettings.setAllowFileAccess(true);//是否可以访问文件协议开头的资源
        webSettings.setAllowContentAccess(true);//是否可以访问contentProvider协议的资源
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAppCacheEnabled(false);
        webSettings.setMinimumFontSize(getResources().getDimensionPixelSize(R.dimen.sp_12));
        //设置默认字体大小
        webSettings.setDefaultFontSize(getResources().getDimensionPixelSize(R.dimen.sp_14));
        //允许跨域访问
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            webSettings.setAllowUniversalAccessFromFileURLs(true);
        //5.0以上打开webView跨域携带cookie的许可
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptThirdPartyCookies(mWebView, true);
        }
    }

//    private WrapperRecyclerView obtain() {
//        WrapperRecyclerView rvWrapper = new WrapperRecyclerView(this);
//        rvWrapper.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//        rvWrapper.setClipToPadding(false);
//        rvWrapper.setPadding(0, 0, 0, getResources().getDimensionPixelSize(R.dimen.dp_40));
//        rvWrapper.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
//        return rvWrapper;
//    }

    private final Runnable mReloadCallback = this::refresh;

    private void refresh() {
        if (mWebView != null) {
            mWebView.reload();
        }
    }

    /**
     * 获取消息详情失败
     */
    @Override
    public void getMessageDetailsFailed(String failed) {
        dismissLoading();
        mContainer.removeAllViews();
        getLayoutInflater().inflate(R.layout.include_empty_page, mContainer, true);
        if (isNoAuth(failed)) {
            noAuthority();
        } else {
            noNetwork(failed);
        }
    }

    @Override
    public void reload() {
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mWebView != null) {
            mWebView.onResume();
            mWebView.resumeTimers();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.onPause();
            mWebView.pauseTimers();
        }
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            //webview调用destory时,webview仍绑定在Activity上.
            // 这是由于自定义webview构建时传入了该Activity的context对象,因此需要先从父容器中移除webview,然后再销毁webview.
            //还可以让webView运行在单独进程中，不用的时候直接system.exit(0)
            mWebView.removeCallbacks(mReloadCallback);
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                //防止内存泄露。
                mWebView.clearHistory();
                ((ViewGroup) mWebView.getParent()).removeView(mWebView);
                mWebView.stopLoading();
                mWebView.setWebChromeClient(null);
                mWebView.setWebViewClient(null);
            }
            mWebView.removeAllViews();
            mWebView.destroy();
        }
        super.onDestroy();
    }

//    private class ImageAdapter extends SuperRecyclerAdapter<String> {
//
//        ImageAdapter(Context context, List<String> dataList) {
//            super(context, dataList);
//        }
//
//        @NonNull
//        @Override
//        protected View bindItemView(int viewType, ViewGroup parent) {
//            ImageView imageView = new ImageView(mContext);
//            imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
//            return imageView;
//        }
//
//        @Override
//        public void onBindHolder(RecyclerHolder holder, String url, int position) {
//            Glide.with(mContext).load(Uri.parse(url)).into((ImageView) holder.itemView);
//        }
//    }
}
